package org.suyafei.func;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.configuration.Configuration;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;
import org.suyafei.model.ShortLinkWideDO;

/**
 * @author 宿某人
 * @Date: 2022/04/01/10:46
 * @Description:
 */
@Slf4j
public class LocationMapFunction extends RichMapFunction<ShortLinkWideDO,String > {

    private static final String IP_PARSE_URL = "https://restapi.amap.com/v3/ip?ip=%s&output=json&key=9f9592098800dd8cf632236ee936761d";


    private CloseableHttpClient client;
    @Override
    public void close() throws Exception {
        if (client != null) {
            client.close();
        }
    }

    @Override
    public void open(Configuration parameters) throws Exception {
        client = this.createHttpClient();
    }

    @Override
    public String map(ShortLinkWideDO value) throws Exception {
        String ip = value.getIp();

        String url = String.format(IP_PARSE_URL, ip);

        HttpGet httpGet = new HttpGet(url);

        try(CloseableHttpResponse response = client.execute(httpGet)) {

            int statusCode = response.getStatusLine().getStatusCode();

            if (statusCode == HttpStatus.SC_OK) {
                HttpEntity entity = response.getEntity();
                String result = EntityUtils.toString(entity, "UTF-8");
                JSONObject locationObj = JSON.parseObject(result);
                String province = locationObj.getString("province");
                String city = locationObj.getString("city");
                value.setCity(city);
                value.setProvince(province);

            }

        } catch (Exception e) {
            log.error("ip解析错误，value={},msg={}", value, e.getMessage());
        }

        return JSON.toJSONString(value);
    }

    /**
     * 创建Http客户端
     * @return
     */
    public CloseableHttpClient createHttpClient() {

        Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("http", PlainConnectionSocketFactory.getSocketFactory())
                .register("https", SSLConnectionSocketFactory.getSocketFactory())
                .build();

        PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(registry);

        //设置连接池最大连接500
        connectionManager.setMaxTotal(500);
        //MaxPerRoute是对MaxTotal的细分，每个主机的并发最大是300 route是指域名
        connectionManager.setDefaultMaxPerRoute(300);
        RequestConfig requestConfig = RequestConfig.custom()
                .setSocketTimeout(20000)
                .setConnectTimeout(10000)
                .setConnectionRequestTimeout(1000).build();
        return HttpClientBuilder.create().setDefaultRequestConfig(requestConfig)
                .setConnectionManager(connectionManager)
                .build();
    }
}
